package com.liangdemo.web.thread;

/**
 * 继承Thread实现多线程
 * 使用同步锁，实现售票员售票问题
 *
 * @author Mr.Liang
 * @date 2022/5/12 10:35
 */

public class ThreadDemo extends Thread {
    public String name;

    ThreadDemo(String name) {
        this.name = name;
    }

    static int tick = 20; // 为了保持票数的一致，票数要静态
    static Object ob = new Object(); // 创建一个静态钥匙 值是任意的

    public void ticket() {
        System.out.println(name + "卖出了第" + tick + "张票");
        tick--;
    }

    public void run() {
        while (tick > 0) {
            synchronized (ob) {
                if (tick > 0) {
                    ticket();
                }
            }
            if (tick == 0) {
                System.out.println("票卖完了");
            }
            try {
                Thread.sleep(100);
            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo threadx = new ThreadDemo("兔子");
        threadx.start();
        ThreadDemo threadx1 = new ThreadDemo("乌龟");
        threadx1.start();
    }

}
